{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. 定义队列及其操作。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "queue = tf.FIFOQueue(100,\"float\")\n",
    "# 把随机数插入到队列中\n",
    "enqueue_op = queue.enqueue([tf.random_normal([1])])\n",
    "# 创建一个5个线程运行队列的入队操作，表示同时启动五个线程把随机数插入队列\n",
    "qr = tf.train.QueueRunner(queue, [enqueue_op] * 5)\n",
    "# 把QueueRunner放到计算图的tf.GraphKeys.QUENE_RUNNERS中\n",
    "tf.train.add_queue_runner(qr)\n",
    "# 定义出队操作\n",
    "out_tensor = queue.dequeue()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 启动线程。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 0.75037265]\n",
      "[-0.09710068]\n",
      "[ 1.1645664]\n",
      "[ 0.09584331]\n",
      "[ 0.86558545]\n"
     ]
    }
   ],
   "source": [
    "with tf.Session() as sess:\n",
    "    # 协同启动线程\n",
    "    coord = tf.train.Coordinator()\n",
    "    # tf.train.start_queue_runners会启动tf.GraphKeys.QUENE_RUNNERS\n",
    "    # 集合中的所有QueueRunner\n",
    "    threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n",
    "    for _ in range(5): \n",
    "        print(sess.run(out_tensor))\n",
    "    # 停止所有线程\n",
    "    coord.request_stop()\n",
    "    coord.join(threads)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
